<template>
  <div class="page-wrap">
    <div class="page-content">
      <el-card class="box-card">
        <template #header>
          <div class="flex">
            <div class="card-header flex-1">资讯导出处理</div>
            <el-link :icon="Download" href="/article-builder/资讯频道导入模板.xlsx" target="_blank">下载模板</el-link>
          </div>
        </template>
        <el-upload :on-change="handleChange" :on-exceed="handleExceed" :accept="'.xlsx'" :limit="1" :auto-upload="false" drag action="#" multiple>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖动文件到此处，或 <em>点击上传</em></div>
        </el-upload>
        <template #footer>
          <el-text size="small">将纯文本正文转换为html格式的正文</el-text>
          <el-divider direction="vertical" />
          <el-text size="small">生成文本摘要</el-text>
          <el-divider direction="vertical" />
          <el-text size="small"><el-link href="https://gitee.com/cvpv/article-builder" target="_blank">https://gitee.com/cvpv/article-builder</el-link></el-text>
        </template>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import * as XLSX from 'xlsx'
import { Download, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, ElNotification } from 'element-plus'

let selectedFile: File

const parseFile = () => {
  const fileReader = new FileReader()

  fileReader.onload = (event) => {
    const data = new Uint8Array(event.target?.result as ArrayBuffer)
    const workbook = XLSX.read(data, { type: 'array' })

    // 获取第一个工作表
    const worksheet = workbook.Sheets[workbook.SheetNames[0]]

    // 将工作表数据转换为JSON对象
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 2 })

    // 处理解析后的数据
    console.log(jsonData)

    // 处理解析后的数据
    const newData = addTestDataColumn(jsonData)
    exportToExcel(newData, 'newData.xlsx')
  }

  selectedFile && fileReader.readAsArrayBuffer(selectedFile)
}

function extractString(str: string) {
  // 将连续空格替换为单个空格
  const strLength = str.length
  str = str.replace(/\s+/g, ' ')

  // 删除换行符
  str = str.replace(/\n/g, '')

  // 提取前120个字符
  str = str.substring(0, 120)

  if (strLength > 120) {
    str += '…'
  }

  return str
}

function textToHtml(text: string) {
  // 替换换行符并用<p>标签包裹非空行
  var html = text.replace(/^(.*)$/gm, function (_match, line) {
    if (line.trim() === '') {
      return '<br>'
    } else {
      return '<p>' + line + '</p>'
    }
  })
  // 替换空格为HTML转义字符
  html = html.replace(/ /g, '&ensp;') // 替换普通空格
  html = html.replace(/\u00A0/g, '&nbsp;') // 替换不间断空格
  html = html.replace(/\u2002/g, '&ensp;') // 替换en空格
  html = html.replace(/\u2003/g, '&emsp;') // 替换em空格
  html = html.replace(/\u3000/g, '&#12288;') // 替换中文空格（全角空格）
  return html
}

const addTestDataColumn = (data: any) => {
  return data.map((row: any, _index: number) => {
    const zheng_wen = row['正文'] || ''
    return {
      ...row,
      摘要: extractString(zheng_wen),
      正文网页: textToHtml(zheng_wen),
    }
  })
}

const exportToExcel = (data: any, filename: string) => {
  ElMessage({
    message: `转换成功！`,
    type: 'success',
  })
  ElNotification({
    title: '提示',
    message: `如果浏览器拦截下载，请点击允许。如果要再次上传请刷新网页，以便清空状态。使用中有任何问题，请联系我。`,
    type: 'info',
    duration: 0,
  })
  const worksheet = XLSX.utils.json_to_sheet(data)
  const newWorkbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(newWorkbook, worksheet, 'Sheet1')
  XLSX.writeFile(newWorkbook, filename)
}

const handleExceed = () => {
  ElMessage({
    message: `最多选择${1}个文件`,
    type: 'warning',
  })
}
const handleChange = (rawFile: any, uploadFiles: any) => {
  console.log('触发改变')
  console.log(rawFile, uploadFiles)
  selectedFile = rawFile.raw
  parseFile()
}
</script>

<style scoped>
.flex {
  display: flex;
}
.flex-1 {
  flex: 1 1 0%;
}
.page-wrap {
  padding: 12vmin 4vmin;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/beams.jpg');
  background-size: cover;
}
.page-content {
  max-width: none;
  margin: 0 auto;
}

/* 移动优先 响应式媒体查询 */
@media (min-width: 768px) {
  .page-wrap {
    padding: 32px;
    padding-top: 200px;
  }
  .page-content {
    max-width: 700px;
  }
}
</style>
